#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File Name: export_blossom.py
# Author: bobo
# Created Time: 20241112
# pip3 install pymysql
"""
导出blossom中的文章
Usage:
    export_blossom.py [-o=<path>] [-u=<user>] [-p=<password>] [-i=<ip>]
    export_blossom.py (-h | --help)
    export_blossom.py (-v | --version)

Options:
    -h --help  显示帮助信息
    -v --version  显示版本信息
    -o <path> 导出目录
    -u <user> 数据库用户名
    -p <password> 数据库密码
    -i <ip> 数据库IP@port，默认3306可以省略
"""

import os

import pymysql
from docopt import docopt
from pymysql.cursors import DictCursor


def _generate_node_info(folder_nodes):
    """
    生成父子目录关系和名称字典
    """
    relation_dict, name_dict = {}, {}
    for node in folder_nodes:
        relation_dict[node["id"]] = node["pid"]
        name_dict[node["id"]] = node["name"]
    return relation_dict, name_dict


def _get_node_path(pid, relation_dict, name_dict):
    """
    查询文章所在目录结构
    """
    path = "./blossom"
    while pid in relation_dict:
        path = os.path.join(path, name_dict[pid])
        path = os.path.abspath(path)
        pid = relation_dict[pid]
    return path


def _write_md(path, md_file, content):
    """
    保存到markdown文件
    """
    if not os.path.exists(path):
        os.system(f"mkdir -p '{path}'")
    full_name = os.path.join(path, md_file)
    with open(full_name, "w", encoding="utf-8") as f:
        f.write(content)
    print(f"导出markdown文件：{full_name}")
    pass


def export_blossom_posts(out_path, user, password, ip, port=3306, database="blossom"):
    """
    导出blossom文章
    """
    # 连接数据库
    conn = pymysql.connect(
        user=user,
        password=password,
        host=ip,
        port=port,
        database=database,
        cursorclass=DictCursor,
    )
    cursor = conn.cursor()

    # 查询目录节点
    sql: str = "select id,pid,name from blossom_folder;"
    cursor.execute(sql)
    folder_nodes = cursor.fetchall()
    relation_dict, name_dict = _generate_node_info(folder_nodes)

    # 查询文章
    sql = "select cre_time,upd_markdown_time,pid,name,markdown from blossom_article;"
    cursor.execute(sql)
    while row := cursor.fetchone():
        path = _get_node_path(row["pid"], relation_dict, name_dict)
        create_time_str = f'{row["cre_time"]}'
        modify_time_str = f'{row["upd_markdown_time"]}'
        md_content = row["markdown"]

        new_head = md_content[:10]
        # 在前50个字符中查询是否有修改时间信息
        if md_content.find("modifytime", 0, 50) == -1:
            new_head = new_head.replace(
                "---\n",
                f"---\ncreatetime: {create_time_str}\nmodifytime: {modify_time_str}\n",
            )
        _write_md(
            os.path.join(out_path, path),
            row["name"] + ".md",
            new_head + md_content[10:],
        )
    # 关闭连接
    cursor.close()
    conn.close()


if __name__ == "__main__":
    arguments = docopt(__doc__, version="export_blossom.py 1.0")
    # print(arguments)

    args = {}
    if out_path := arguments.get("-o"):
        args["out_path"] = out_path
    else:
        args["out_path"] = "./"
    user = arguments.get("-u")
    args["user"] = user

    pwd = arguments.get("-p")
    args["password"] = pwd

    ip = arguments.get("-i").split("@")
    if len(ip) == 1:
        args["ip"] = ip[0]
        args["port"] = 3306
    else:
        args["ip"] = ip[0]
        args["port"] = int(ip[1])

    print(args)
    export_blossom_posts(**args)
